﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BbsbWebService.Classes;

namespace BbsbWebService.Repositories.Server
{
    public abstract class ServerRepositoryBase<T> : RepositoryBase<T> where T : BaseItem
    {
        public override void SaveItem(T item)
        {
            if (!string.IsNullOrEmpty(item.Name))
            {
                if (HasItem(item.Id))
                {
                    // update
                    for (int i = 0; i < Items.Count; i++)
                    {
                        if (Items[i].Id == item.Id)
                        {
                            Items[i] = item;
                            break;
                        }
                    }
                }
                else
                {
                    // new item
                    if (item.Id == Guid.Empty)
                        item.Id = Guid.NewGuid();
                    Items.Add(item);
                }
                AppSettings.Instance.Save();
            }
        }

        public override void RemoveItem(T item)
        {
            int index = Items.GetIndexOfItem(i => i.Id == item.Id);
            if (index != -1)
            {
                Items.RemoveAt(index);
                AppSettings.Instance.Save();
            }
        }
    }
}
